import xml.etree.ElementTree as ET

from zeus.operation_service.app.core.asset.tools.xmltodict import xml_to_dict
from zeus.operation_service.app.core.asset.asset_exception import AssetError
from zeus.operation_service.app.core.framework.common.result_code import AssetOperationResultCode
from vulcanus.log.log import LOGGER


class SceneParse:
    def __init__(self, xml_path):
        self._xml_path = xml_path
        self._collect_items = dict()

    def get_collect_items(self):
        try:
            xml_tree = ET.parse(self._xml_path)
            self.parse_collect_items(xml_tree.getroot())
        except Exception as e:
            LOGGER.error("get_collect_items failed, error: %s", e)
            raise AssetError(AssetOperationResultCode.ERR_ASSETS_SCENE_PARSE)
        else:
            return self._collect_items

    def parse_collect_items(self, xml_root):
        for child in xml_root:
            if child.tag == "SCENE" or child.tag == "SERVERTYPE":
                self.parse_collect_items(child)
            elif child.tag == "CHECKITEM":
                if 'isDir' in child.attrib.keys() and child.attrib['isDir'] == 'true':
                    self.parse_collect_items(child)
                else:
                    self._collect_items[child.attrib.get('id')] = child.attrib.get('name_en')


class ItemParse:
    def __init__(self, xml_path):
        self._xml_path = xml_path
        self._item_info = str()

    def get_item_info(self):
        try:
            parsed_data = xml_to_dict(self._xml_path)
            self._item_info = parsed_data['info']
        except Exception as e:
            LOGGER.error("get_item_info failed, error: %s", e)
            raise AssetError(AssetOperationResultCode.ERR_ASSETS_ITEM_PARSE)
        else:
            return self._item_info
